using System;
using System.Collections.Generic;
using System.IO;
using OFX.Aggregator.Infrastructure;

namespace OFX.Aggregator.Implementation
{
	public class RegexPatternProviderFromTSV : IRegexPatternProvider
	{
		private readonly Dictionary<string, string> matchNameToRegExPattern = new Dictionary<string, string>();

		public RegexPatternProviderFromTSV(string regexFilePath)
		{
			var separators = new[] {'\t'};

			using (TextReader reader = new StreamReader(regexFilePath, true))
			{
				for (;;)
				{
					string line = reader.ReadLine();

					if (line == null)
						break;

					string[] splits = line.Split(separators, 2);

					if (splits.Length != 2)
						throw new ArgumentException("Line does not contain two tab-separated strings.", "regexFilePath");

					string patternName = splits[0].Trim();
					if (patternName.StartsWith("'")) // Ignore comments
						continue;

					string pattern = splits[1].Trim(separators);

					this.matchNameToRegExPattern.Add(patternName, pattern);
				}
			}
		}

		#region IRegexPatternProvider Members

		public string GetMatchPattern(string matchName)
		{
			return this.matchNameToRegExPattern[matchName];
		}

		#endregion
	}
}